package com.lechuang.user.manager.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.lechuang.common.model.BaseEntity;
import com.lechuang.common.result.Result;
import com.lechuang.member.dto.SaveMemberDto;
import com.lechuang.member.feign.MemberFeign;
import com.lechuang.member.vo.MemberDictCommonVo;
import com.lechuang.redis.utils.RedisUtils;
import com.lechuang.user.constants.LoginConstants;
import com.lechuang.user.dto.*;
import com.lechuang.user.entity.User;
import com.lechuang.user.enums.UserAuthStatusEnum;
import com.lechuang.user.manager.UserManager;
import com.lechuang.user.service.UserService;
import com.lechuang.user.util.InviteCodeBuildUtil;
import com.lechuang.user.vo.UserDetailVo;
import com.lechuang.user.vo.UserVo;
import com.lechuang.web.exception.BusinessException;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Objects;
import java.util.Random;

/**
 * @author apple
 * @version 1.0
 * @date 2024/6/21
 */
@Service
@Log4j2
public class UserManagerImpl implements UserManager {

    @Resource
    private UserService userService;
    @Resource
    private MemberFeign memberFeign;

    @Value("${user.avatar}")
    private String avatar;
    @Value("${user.nickName}")
    private String nickName;


    @Override
    public UserVo queryById(Long id) {
        User user = userService.getById(id);
        UserVo userVo = BeanUtil.copyProperties(user, UserVo.class);
        return userVo;
    }

    @Override
    public void updateById(EditUserDto editUserDto) {
        User user = userService.getById(editUserDto.getId());
        if (Objects.isNull(user)){
            throw new BusinessException("用户信息查询为空");
        }
        User updateUser = BeanUtil.copyProperties(editUserDto, User.class);
        userService.updateById(updateUser);
        SaveMemberDto saveMemberDto = BeanUtil.copyProperties(editUserDto, SaveMemberDto.class);
        saveMemberDto.setId(null);
        saveMemberDto.setUserId(editUserDto.getId());
        saveMemberDto.setStatus(BaseEntity.STATUS_NORMAL);
        memberFeign.updateMemberByUserId(saveMemberDto);
    }

    @Override
    public void editLoginPwd(String token, EditLoginPwdDto editLoginPwdDto) {
        Long id = editLoginPwdDto.getId();
        String loginPassword = editLoginPwdDto.getLoginPassword();
        String confirmLoginPassword = editLoginPwdDto.getConfirmLoginPassword();
        String oldLoginPassword = editLoginPwdDto.getOldLoginPassword();


        User user = userService.getById(editLoginPwdDto.getId());
        if (Objects.isNull(user)){
            throw new BusinessException("用户信息查询为空");
        }
        if (!Objects.equals(loginPassword,confirmLoginPassword)){
            throw new BusinessException("新密码输入不一致");
        }
        //TODO:密码加密
       // String userloginPassword = DigestUtils.md5Hex(oldLoginPassword);
        String userloginPassword =user.getLoginPassword();
        if (!Objects.equals(user.getLoginPassword(),userloginPassword)){
            throw new BusinessException("旧密码输入不一致");
        }
        loginPassword = DigestUtils.md5Hex(loginPassword);

        User updateUser =  new User()
                .setLoginPassword(loginPassword);
        updateUser.setId(id);
        userService.updateById(updateUser);
        SaveMemberDto saveMemberDto = BeanUtil.copyProperties(updateUser, SaveMemberDto.class);
        saveMemberDto.setId(null);
        saveMemberDto.setUserId(id);
        saveMemberDto.setStatus(BaseEntity.STATUS_NORMAL);
        memberFeign.updateMemberByUserId(saveMemberDto);
    }

    @Override
    public void editPayPwd(EditPayPwdDto editPayPwdDto) {
        Long id = editPayPwdDto.getId();
        String payPassword = editPayPwdDto.getPayPassword();
        String validateCode = editPayPwdDto.getValidateCode();
        String phone = editPayPwdDto.getPhone();

        User user = userService.getById(id);
        if (Objects.isNull(user)){
            throw new BusinessException("用户信息查询为空");
        }
        String userPhone = user.getPhone();
        if (!Objects.equals(userPhone,phone)){
            throw new BusinessException("用户手机号错误");
        }

        //验证码验证
//        String  editPayKey = LoginConstants.PAY_KEY + phone;
//        Object redisValidateCode = RedisUtils.get(editPayKey);
//        if (Objects.isNull(redisValidateCode)) {
//            throw new BusinessException("验证码不存在或已过期，请重新获取!");
//        }
//        if (!Objects.equals(validateCode, redisValidateCode)) {
//            throw new BusinessException("验证码输入错误!");
//        }
        // TODO:待加密
        //  payPassword = DigestUtils.md5Hex(payPassword);
        User updateUser = new User().setPayPassword(payPassword);
        updateUser.setId(id);
        userService.updateById(updateUser);

        SaveMemberDto saveMemberDto = BeanUtil.copyProperties(updateUser, SaveMemberDto.class);
        saveMemberDto.setId(null);
        saveMemberDto.setUserId(id);
        saveMemberDto.setStatus(BaseEntity.STATUS_NORMAL);
        memberFeign.updateMemberByUserId(saveMemberDto);
    }



    @Override
    public UserDetailVo queryUserDetailByPhone(String phone) {
        User user = userService.queryByPhone(phone);
        UserDetailVo userDetailVo = BeanUtil.copyProperties(user, UserDetailVo.class);
        return userDetailVo;
    }

    @Override
    public void updateUser(UpdateUserDto updateUserDto) {
        Long id = updateUserDto.getId();
        User user = userService.getById(id);
        if (Objects.isNull(user)){
            throw new BusinessException("用户信息查询为空");
        }
        User updateUser = BeanUtil.copyProperties(updateUserDto, User.class);
        userService.updateById(updateUser);
    }

    @Override
    public UserVo selectById(UserQueryDto userQueryDto) {
        Long id = userQueryDto.getId();
        User user = userService.getById(id);
        UserVo userVo = BeanUtil.copyProperties(user, UserVo.class);
        return userVo;
    }

    @Override
    public void editBankInfo(EditUserDto editUserDto) {
        Long id = editUserDto.getId();
        User user = userService.getById(id);
        if (Objects.isNull(user)){
            throw new BusinessException("用户信息查询为空");
        }
        User updateUser = BeanUtil.copyProperties(editUserDto, User.class);
        userService.updateById(updateUser);
        SaveMemberDto saveMemberDto = BeanUtil.copyProperties(editUserDto, SaveMemberDto.class);
        saveMemberDto.setUserId(id);
        memberFeign.updateMemberByUserId(saveMemberDto);
    }

    @Override
    public void userAuth(UserAuthDto userAuthDto) {
        Long id = userAuthDto.getId();
        User user = userService.getById(id);
        if (Objects.isNull(user)){
            throw new BusinessException("用户信息查询为空");
        }
        Integer authStatus = user.getAuthStatus();
        if (UserAuthStatusEnum.AUTH_SUCCESS.getId().equals(authStatus)||UserAuthStatusEnum.AUTH_ING.getId().equals(authStatus)){
            throw new BusinessException("认证状态:"+UserAuthStatusEnum.getByValue(authStatus)+"，不能更改");
        }
        User updateUser =new User()
                .setRealName(userAuthDto.getRealName())
                .setIdentityNo(userAuthDto.getIdentityNo())
                .setIdentityFrontUrl(userAuthDto.getIdentityFrontUrl())
                .setIdentityReverseUrl(userAuthDto.getIdentityReverseUrl())
                .setAuthStatus(UserAuthStatusEnum.AUTH_ING.getId());
        updateUser.setId(id);
        userService.updateById(updateUser);
        SaveMemberDto saveMemberDto = BeanUtil.copyProperties(updateUser, SaveMemberDto.class);
        saveMemberDto.setId(null);
        saveMemberDto.setUserId(id);
        saveMemberDto.setStatus(BaseEntity.STATUS_NORMAL);
        memberFeign.updateMemberByUserId(saveMemberDto);
    }

    @Override
    public void registerByPhone(RegisterByPhoneDto registerByPhoneDto) {
        String phone = registerByPhoneDto.getPhone();
        String loginPassword = registerByPhoneDto.getLoginPassword();
         //TODO:待加密
        //loginPassword = DigestUtils.md5Hex(loginPassword);
        String invitePhone = registerByPhoneDto.getInvitePhone();
        User user = userService.queryByPhone(phone);
        if (Objects.nonNull(user)){
            throw new BusinessException("该手机号已注册");
        }
        User inviteUser = userService.queryByPhone(invitePhone);
        if (Objects.isNull(inviteUser)){
            throw new BusinessException("该邀请人手机号未注册");
        }
        User insertUser =new User()
                .setAvatar(avatar)
                .setNickName(nickName)
                .setPhone(phone)
                .setLoginPassword(loginPassword)
                .setInviteUserId(inviteUser.getId());
        this.saveUser(insertUser);
    }

    @Override
    public void saveUser(User insertUser) {
        String randomInviteCode = InviteCodeBuildUtil.toSerialCode(new Random().nextLong());
        insertUser.setInviteCode(randomInviteCode);
        Result<MemberDictCommonVo> memberDictCommonVoResult = memberFeign.queryDefaultDict();
        if (Objects.nonNull(memberDictCommonVoResult) && Objects.nonNull(memberDictCommonVoResult.getData())){
            MemberDictCommonVo memberDictCommonVo = memberDictCommonVoResult.getData();
            insertUser.setGroupBuyLevelId(memberDictCommonVo.getGroupBuyLevelId());
            insertUser.setGroupBuyLevelName(memberDictCommonVo.getGroupBuyLevelName());
            insertUser.setMemberStartLevelId(memberDictCommonVo.getMemberStartLevelId());
            insertUser.setMemberStartLevelName(memberDictCommonVo.getMemberStartLevelName());
            insertUser.setMemberLevelId(memberDictCommonVo.getMemberLevelId());
            insertUser.setMemberLevelName(memberDictCommonVo.getMemberLevelName());
        }
        userService.save(insertUser);
        User saveUser = userService.queryByPhone(insertUser.getPhone());
        SaveMemberDto saveMemberDto =new SaveMemberDto();
        BeanUtil.copyProperties(insertUser,saveMemberDto);
        saveMemberDto.setUserId(saveUser.getId());
        memberFeign.saveMember(saveMemberDto);
    }
}
